import cherrypy
import sys
import time
from datetime import datetime
from threading import Timer
import LightSnake
from cherrypy.process import plugins
import urllib2
try:
    import settings
except ImportError:
    print "copy settings_template.py to settings.py."
    raise
 
RED = 0
GREEN = 1
BLUE = 2

class JenkinsClient(plugins.SimplePlugin):
    """
    Client of jenkins reading from jenkins directly using python API
    """
    
    def __init__(self, snake, bus):
        plugins.SimplePlugin.__init__(self, bus)
        self.timer = None
        self.snake = snake

    @cherrypy.expose
    def index(self):
        """
        Main index Handler.
        """
        return "Sorry nothing returned yet for Jenkins"

    def set_value(self, project, color, value):
        num = project * 3 + color
        self.snake.set(num, value)

    def set_white(self, project):
        self.set_value(project, RED, 254)
        self.set_value(project, GREEN, 128)
        self.set_value(project, BLUE, 254)        
        
    def set_disabled(self, project):
        self.set_value(project, RED, 0)
        self.set_value(project, GREEN, 0)
        self.set_value(project, BLUE, 0)        

    def set_green(self, project):
        self.set_value(project, RED, 0)
        self.set_value(project, GREEN, 128)
        self.set_value(project, BLUE, 0)

    def set_blue(self, project):
        self.set_value(project, RED, 0)
        self.set_value(project, GREEN, 0)
        self.set_value(project, BLUE, 254)

    def set_red(self, project):
        self.set_value(project, RED, 254)
        self.set_value(project, GREEN, 0)
        self.set_value(project, BLUE, 0)

    def set_project_from_color(self, project, name, color):
        sys.stderr.write("Setting project: " + str(project) + " : " +  name +  " : " + color  + "\n")
        if ("disabled" == color):
            self.set_disabled(project)
        elif ("blue" == color):  
            self.set_green(project)
        elif ("yellow" == color):  
            self.set_blue(project)
        elif ("red" == color):
            self.set_red(project)
     
    def read_jenkins(self):
        '''
        Reads jenkins from remote
        '''
        try:
            sys.stderr.write("Reading jenkins: " + str(datetime.now()) + "\n")
            password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
            password_mgr.add_password(None, settings.JENKINS_FEED, settings.JENKINS_USER, settings.JENKINS_PASSWORD)
            handler = urllib2.HTTPBasicAuthHandler(password_mgr)
            opener = urllib2.build_opener(handler)
            urllib2.install_opener(opener)
            entries = eval(urllib2.urlopen(settings.JENKINS_FEED + "api/python").read())
            current_index = 0
            for entry in entries['jobs']:
                name = entry['name']
                if not name.startswith("_"): # skip templates
                    self.set_project_from_color(current_index, name, entry['color'])
                    time.sleep(0.02)
                    current_index +=1
            for i in range(current_index, settings.MAX_PROJECTS):
                self.set_disabled(i)
            sys.stderr.write("Finished reading jenkins: " + str(datetime.now()) + "\n")
        except Exception:
            for i in range(0, settings.MAX_PROJECTS):
                self.set_white(i)
        finally:
            self.timer = Timer(15, self.read_jenkins) # refresh every 15 sec
            self.timer.start()

    def stop(self):
        '''
        Stops the calendar object. Kills all the outstanding threads.
        '''
        self.bus.log("Stopping jenkins reader.") #pylint: disable-msg=E1101
        if self.timer is not None:
            self.timer.cancel()

    def start(self):
        """ Starts timer """
        # start reading data in another thread
        self.timer = Timer(0, self.read_jenkins)
        self.timer.start()
        self.bus.log("Starting jenkins.") #pylint: disable-msg=E1101

    def graceful(self):
        """Stops and restart timer."""
        self.stop()
        self.start()

class Set:
    def __init__(self, snake):
        self.snake = snake
        indexFile = open ('./index.htm', 'r+')
        self.index = indexFile.read()
        
        @cherrypy.expose
        def default(self, channel, power):
            print "Channel: " + channel + " Power: " + power
            self.snake.set(channel, power)
            return self.index

class Root(): #pylint: disable-msg=R0903
    """
    Root object for the whole hierarchy of handlers.
    """
    
    def __init__(self):
        serial_device = settings.SERIAL_DEVICE
        serial_speed = settings.SERIAL_SPEED
        debug = settings.DEBUG
        self.light_snake = LightSnake.LightSnake(serial_device, serial_speed, channelNumber=settings.MAX_PROJECTS * 3, debug=debug)
        self.set = Set(self.light_snake)
        self.jenkins = JenkinsClient(self.light_snake, cherrypy.engine)
        self.jenkins.subscribe() #pylint: disable-msg=E1101

    @cherrypy.expose
    def index(self):
        return self.index

if __name__ == '__main__':
    cherrypy.config.update({"server.socket_port" : 8085})
    cherrypy.quickstart(root=Root(), script_name="/")
